package com.example.gateway;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * <b>TODO . </b>
 *
 * @author yangyl11
 * @version 1.0.0
 * @date 2021/5/10
 * @since JDK 1.8
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

		String token = exchange.getRequest().getQueryParams().getFirst("token");
		if (token == null || token.isEmpty()) {
			exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
			return exchange.getResponse().writeWith(Flux.just(exchange.getResponse().bufferFactory().wrap("token is empty".getBytes(StandardCharsets.UTF_8))));
		}
		return chain.filter(exchange);
	}

	/**
	 * 设定过滤器优先级别，值越小则优先级越高
	 *
	 * @return
	 */
	@Override
	public int getOrder() {

		return 0;
	}
}

